<?php

class SiteController extends Controller
{
    public $layout = 'topColumn';

	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
				'minLength'=>4,
				'maxLength'=>4,
                'testLimit'=>1,
                'width'=>'100px',
            ),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
    }

    public function actionTranslationSelect()
    {
 /*       if(isset($_POST['language']))
        {
            $session = Yii::app()->session;
            $sid = Yii::app()->session->sessionID;
            $session[$sid]= array('language'=>$_POST['language']);
        }*/
    }
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
    {
        $model=new LoginForm;
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
	$xqhz = Achievement::model()->findAll("type_id = ".Achievement::TYPE_XQHZ);
	$kycg = Achievement::model()->findAll("type_id = ".Achievement::TYPE_KYCG);
	foreach($xqhz as $elem)
	{
		$xqhz_array[] = array('title'=>$elem->title, 'view_url'=>'/achievement/'.$elem->id);
	}
	foreach($kycg as $elem)
	{
		$kycg_array[] = array('title'=>$elem->title, 'view_url'=>'/achievement/'.$elem->id);
	}
        $this->render('index',
            array(
                'model'=>$model,
		'xqhz_array'=>$xqhz_array,
		'kycg_array'=>$kycg_array,
            ));
    }

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
    {

        $model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
            $model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
        }
        /**
         * login for loginModal
         * @author : nonglei
         * @date   : 20/03/2014
         */
        if(isset($_POST['username']))
        {
			$username=$_POST['username'];
			$password=$_POST['password'];
            $rememberMe=$_POST['remenberme'];
			$UI=new UserIdentity($username,$password);
			$UI->authenticate();
			$errorCode=$UI->errorCode;
			$response=$errorCode;
			if($errorCode==UserIdentity::ERROR_NONE)
			{
				$model=new LoginForm;
				$model->password=$password;
				$model->username=$username;
				$model->rememberMe=$rememberMe=='true'?1:0;
				if($model->validate() && $model->login());
			}
            echo $response;
            return;
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}
    /*
     * 显示弹窗登录页面
     *
     */
    public function actionAjaxLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
            if($model->validate() && $model->login())
            {
                echo 'success';
                return;
            }
        }

		// display the login form
		$this->renderPartial('ajaxlogin',array('model'=>$model));
	}

    public function actionSearch()
    {
	    if(isset($_GET['search']))
	    {
            echo '\'%'.$_GET['search'].'%\'';
		    $dataProvider=new CActiveDataProvider('News',
				    array(
					    'criteria'=>array(
						    'condition'=>'title like :search',
                            'params' => array(':search'=>'%'.$_GET['search'].'%'),
                        )
                    ));
		$this->render('search',array('dataProvider'=>$dataProvider));
	    }
    }

    /**
     * 用于检测用户是否活着
     * @author : nonglei
     * @date   : 20/03/2014
     */
    public function actionAliveResponse()
    {
        if(isset($_POST['ImAlive']))
        {
           /* if(!yii::app()->user->isGuest == 1)
            {
                    Online::model()->updateByPk(yii::app()->user->id,
                    array('LastActiveTime'=>new CDbExpression('NOW()')
                    )
                );
            }*/
           // $response="OK";
           // echo $response;
        }
    }

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}
